/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import dao.ClasseDAO;
import dao.FamiliaDAO;
import dao.MaterialDAO;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import model.Classe;
import model.Familia;
import model.Material;
import model.MaterialDoProduto;

/**
 *
 * @author JONATAS
 */
public class MaterialDialog extends javax.swing.JDialog {

    /**
     * Creates new form ClasseDialog
     */
    public MaterialDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        buscarClassesCB();       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        tbDescricao = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        btnBuscar = new javax.swing.JButton();
        cmbClasse = new javax.swing.JComboBox();
        cmbFamilia = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        tbCodigo = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consulta de Materiais");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Descrição", "Classe", "Família", "Unidade de Medida"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbDescricaoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbDescricaoKeyReleased(evt);
            }
        });

        jLabel3.setText("Família");

        jLabel1.setText("Descrição:");

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        cmbClasse.setFocusCycleRoot(true);
        cmbClasse.setOpaque(false);
        cmbClasse.setRequestFocusEnabled(false);
        cmbClasse.setVerifyInputWhenFocusTarget(false);
        cmbClasse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbClasseActionPerformed(evt);
            }
        });
        cmbClasse.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbClasseKeyPressed(evt);
            }
        });

        cmbFamilia.setFocusCycleRoot(true);
        cmbFamilia.setOpaque(false);
        cmbFamilia.setRequestFocusEnabled(false);
        cmbFamilia.setVerifyInputWhenFocusTarget(false);
        cmbFamilia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFamiliaActionPerformed(evt);
            }
        });
        cmbFamilia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbFamiliaKeyPressed(evt);
            }
        });

        jLabel2.setText("Classe:");

        jLabel5.setText("Código:");

        tbCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbCodigoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbCodigoKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1))
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(tbCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(143, 143, 143))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(tbDescricao)
                                .addContainerGap())))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cmbFamilia, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cmbClasse, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(tbCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tbDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbClasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbFamilia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(btnBuscar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.setText("Selecionar");

        jButton2.setText("Imprimir");

        jLabel4.setText("Filtros:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 712, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(10, 10, 10))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-754)/2, (screenSize.height-544)/2, 754, 544);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
       
        List<Material> lista = new MaterialDAO().findAll();
        
        DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
        modelo.setNumRows(0);
        
        for(Material m : lista){
            modelo.addRow( new String[] {""+m.getMat_codigoCompleto(), m.getMat_descricao(), m.getMat_classe().getCla_descricao(), m.getMat_familia().getFam_descricao(), m.getMat_unidadeMedida().getUnm_sigla()} );         
        }
    }//GEN-LAST:event_formWindowOpened

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if(evt.getClickCount() == 2)
        {
            int linha = jTable1.getSelectedRow();
            String codigo =   ""+jTable1.getValueAt(linha, 0);           
                        
            this.materialComponente = new Material();
            this.materialComponente.setMat_codigoCompleto(codigo);
            
            materialComponente = new MaterialDAO().findByIdComposta(materialComponente.getMat_id());
                        
            this.setVisible(false);
                               
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        
        //List<Material> lista = new MaterialDAO().findByDescricao(tbFiltro.getText() );
        Classe classe = new Classe();         
        Familia fam = new Familia();
        classe.setCla_id(null);

        if(cmbClasse.getSelectedIndex() == 0 || cmbClasse.getSelectedIndex() == -1){
            classe.setCla_id(null);
        }else{            
            classe = ((Classe)cmbClasse.getModel().getSelectedItem());
        }
        System.out.println("Id da familia selecionada: ->"+cmbFamilia.getSelectedIndex());
        if(cmbFamilia.getSelectedIndex() == 0 || cmbFamilia.getSelectedIndex() == -1){
            fam.setFam_id(null);
        }else{            
            fam = ((Familia)cmbFamilia.getModel().getSelectedItem());
        }
        ClasseDAO cdao = new ClasseDAO();
        System.out.println("CLA_ID a ser carregado -> "+ classe.getCla_id());        
        
        List<Material> lista = new MaterialDAO().findComplete(tbCodigo.getText(), tbDescricao.getText(), classe, fam);
        
        DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
        modelo.setNumRows(0);
        
        for(Material m : lista){
            modelo.addRow( new String[] {""+m.getMat_codigoCompleto(), m.getMat_descricao(), m.getMat_classe().getCla_descricao(), m.getMat_familia().getFam_descricao(), m.getMat_unidadeMedida().getUnm_sigla()} );         
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void tbDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbDescricaoKeyPressed
        
    }//GEN-LAST:event_tbDescricaoKeyPressed

    
    private void buscarClassesCB() {

        //List<Marca> lista = new MarcaDAO().findAll();        
        Vector v = new Vector();
        v.add(0, "Todos");
        Vector vt = new Vector(new ClasseDAO().findAll());
        Vector vmodel = new Vector();

        int i = 0;
        for (i = 0; i < 1; i++) {
            System.out.println("Set pos " + i);
            vmodel.add(i, v.get(i));
            System.out.println("Set pos " + i);
        }
        for (int l = 0; l < vt.size(); l++) {
            vmodel.add(i, vt.get(l));
            System.out.println("Set pos " + i);
            i++;
        }

        DefaultComboBoxModel cmodel = new DefaultComboBoxModel(vmodel);
        cmbClasse.setModel(cmodel);

    }

    private void buscarFamiliasCB(String cla_id) {

        Vector v = new Vector();
        v.add(0, "Todos");
        Vector vt = new Vector(new FamiliaDAO().findByClasse(cla_id));
        Vector vmodel = new Vector();

        int i = 0;
        for (i = 0; i < 1; i++) {
            System.out.println("Set pos " + i);
            vmodel.add(i, v.get(i));
            System.out.println("Set pos " + i);
        }
        for (int l = 0; l < vt.size(); l++) {
            vmodel.add(i, vt.get(l));
            System.out.println("Set pos " + i);
            i++;
        }

        DefaultComboBoxModel fmodel;
        fmodel = new DefaultComboBoxModel(vmodel);


        cmbFamilia.setModel(fmodel);
    }
    
    private void tbDescricaoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbDescricaoKeyReleased
        //btnBuscarActionPerformed(null);
    }//GEN-LAST:event_tbDescricaoKeyReleased

    private void cmbClasseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbClasseActionPerformed

        Classe cla = new Classe();
        if (cmbClasse.getSelectedIndex() != 0) {
            cla = new Classe();
            cla = (Classe) cmbClasse.getSelectedItem();
            System.out.println("Cla_id da classe sleecionada -> " + cla.getCla_id());
            buscarFamiliasCB(cla.getCla_id());            
        } else {
            buscarFamiliasCB(null);
        }
    }//GEN-LAST:event_cmbClasseActionPerformed

    private void cmbClasseKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbClasseKeyPressed
        /*
         * if (evt.getKeyCode() == KeyEvent.VK_ENTER) { // Se pressionar enter
         * éo mesmo que clicar no botao salvar btnSalvarActionPerformed(null); }
         */
        /*if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { // Se pressionar ESQ é o mesmo que Cancelar
            btnCancelarActionPerformed(null);
        }*/
    }//GEN-LAST:event_cmbClasseKeyPressed

    private void cmbFamiliaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFamiliaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbFamiliaActionPerformed

    private void cmbFamiliaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbFamiliaKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbFamiliaKeyPressed

    private void tbCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbCodigoKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_tbCodigoKeyPressed

    private void tbCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_tbCodigoKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MaterialDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MaterialDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MaterialDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MaterialDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                MaterialDialog dialog = new MaterialDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    private Material materialComponente = new Material();
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JComboBox cmbClasse;
    private javax.swing.JComboBox cmbFamilia;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField tbCodigo;
    private javax.swing.JTextField tbDescricao;
    // End of variables declaration//GEN-END:variables

    public Material getMaterialComponente() {
        return materialComponente;
    }

    public void setMaterialComponente(Material materialComponente) {
        this.materialComponente = materialComponente;
    }

    
}
